package mapEditor.view.resItemEdit
{
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.ui.Keyboard;
	import flash.utils.Timer;
	
	import iso.IsoBox;
	import iso.IsoDisplayObject;
	import iso.IsoGrid;
	import iso.IsoGridTile;
	import iso.IsoPoint;
	import iso.IsoUtils;
	
	import keyboard.KeyComboCell;
	import keyboard.KeyEvent;
	import keyboard.KeyboardFactory;
	
	import mapEditor.MapEditorManager;
	import mapEditor.data.ConfigTemplateInfo;
	import mapEditor.events.MapEditorEvent;
	import mapEditor.vo.AssetVO;
	import mapEditor.vo.MapTerrainTileVO;
	import mapEditor.vo.ResItemItemVO;
	import mapEditor.vo.ResItemVO;
	import mapEditor.vo.ToolType;
	
	import stages.StageReflection;
	
	import utils.DisplayUtil;
	
	public class ItemEditView extends Sprite
	{
		/**
		 *地图网格层 
		 */		
		private var _mapGridLayer:IsoGrid;
		/**
		 *资源存放层 
		 */		
		private var _assetLayer:IsoDisplayObject;
		private var _gridRow:int=1;
		private var _gridCols:int=1;
		/**
		 *编辑区大小 
		 */
		private var _areaRec:Rectangle;
		private var _resItemVO:ResItemVO;
		private var _items:Vector.<ResItemEditItemView>=new Vector.<ResItemEditItemView>();
		/**
		 *当前选中项的列表 
		 */		
		private var _selectResItemEditItemList:Vector.<ResItemEditItemView>=new Vector.<ResItemEditItemView>();
		
		private var _dragRec:Rectangle=new Rectangle();
		private var _dragRecLayer:Shape;
		private var _moveTimer:Timer=new Timer(80);
		private var _moveSelectType:int;
		/**
		 *当前选中的格子列表 
		 */
		private var _selectGridList:Array=[];
		private var _overGridTile:IsoGridTile;
		private var _gridBoxList:Vector.<IsoBox>=new Vector.<IsoBox>();
		
		public function ItemEditView(areaRec:Rectangle)
		{
			_areaRec=areaRec;
			setView();
			addEvent();
		}
		
		private function setView():void
		{
			drawEditArea();
			_assetLayer=new IsoDisplayObject();
			_mapGridLayer=new IsoGrid(2, ConfigTemplateInfo.instance.mapVO.tileSize, 1, 1, true);
			_mapGridLayer.x=_assetLayer.x=(_areaRec.width-_mapGridLayer.width)/2 + _mapGridLayer.width/2;
			_overGridTile=new IsoGridTile(ConfigTemplateInfo.instance.mapVO.tileSize, 0x000000);
			_overGridTile.visible=false;
			_mapGridLayer.addChild(_overGridTile);
			addChild(_assetLayer);
			addChild(_mapGridLayer);
			
			_dragRecLayer=new Shape();
			addChild(_dragRecLayer);
			
			resetEditAreaInfo();
		}
		
		private function addEvent():void
		{
			MapEditorManager.instance.mapEditorModel.editAreaVO.addEventListener(Event.CHANGE, __onEditAreaChange);
			MapEditorManager.instance.addEventListener(MapEditorEvent.RES_ITEM_ITEM_SELECTED, __onResItemItemSelected);
			MapEditorManager.instance.addEventListener(MapEditorEvent.ASSET_ITEM_SELECTED, __onResItemItemAssetItemSelected);
			MapEditorManager.instance.mapEditorModel.addEventListener(MapEditorEvent.TOOL_TYPE_CHANGE, __onToolTypeChange);
			addEventListener(MouseEvent.MOUSE_MOVE, __onMouseMove);
			addEventListener(MouseEvent.MOUSE_DOWN, __onMouseDown);
			addEventListener(MouseEvent.MOUSE_OUT, __onMouseOut);
			KeyboardFactory.Instance.addKeyCombo("itemSelectItemMove");
			KeyboardFactory.Instance.addEventListener(KeyEvent.COMBO_ALL_KEY_DOWN, __onComboAllKeyDown);
			KeyboardFactory.Instance.addEventListener(KeyEvent.KEY_UP, __onKeyUp);
			KeyboardFactory.Instance.createCombosKey("itemSelectItemMove", [Keyboard.UP], Keyboard.UP);
			KeyboardFactory.Instance.createCombosKey("itemSelectItemMove", [Keyboard.DOWN], Keyboard.DOWN);
			KeyboardFactory.Instance.createCombosKey("itemSelectItemMove", [Keyboard.LEFT], Keyboard.LEFT);
			KeyboardFactory.Instance.createCombosKey("itemSelectItemMove", [Keyboard.RIGHT], Keyboard.RIGHT);
			//			StageReflection.stage.addEventListener(MouseEvent.MOUSE_UP, __onStageMouseUp);
		}
		
		private function removeEvent():void
		{
			MapEditorManager.instance.mapEditorModel.editAreaVO.removeEventListener(Event.CHANGE, __onEditAreaChange);
			MapEditorManager.instance.removeEventListener(MapEditorEvent.RES_ITEM_ITEM_SELECTED, __onResItemItemSelected);
			MapEditorManager.instance.removeEventListener(MapEditorEvent.ASSET_ITEM_SELECTED, __onResItemItemAssetItemSelected);
			MapEditorManager.instance.mapEditorModel.removeEventListener(MapEditorEvent.TOOL_TYPE_CHANGE, __onToolTypeChange);
			removeEventListener(MouseEvent.MOUSE_DOWN, __onMouseDown);
			removeEventListener(MouseEvent.MOUSE_MOVE, __onMouseMove)
			removeEventListener(MouseEvent.MOUSE_UP, __onMouseUp);
			//			StageReflection.stage.removeEventListener(MouseEvent.MOUSE_UP, __onStageMouseUp);
			removeEventListener(MouseEvent.MOUSE_OUT, __onMouseOut);
			KeyboardFactory.Instance.removeEventListener(KeyEvent.COMBO_ALL_KEY_DOWN, __onComboAllKeyDown);
			KeyboardFactory.Instance.removeEventListener(KeyEvent.KEY_UP, __onKeyUp);
			KeyboardFactory.Instance.removeKeyCombo("itemSelectItemMove");
			_mapGridLayer.removeEventListener(MouseEvent.CLICK, __onGridLayerMouseEvent);
			_mapGridLayer.removeEventListener(MouseEvent.MOUSE_MOVE, __onGridLayerMouseEvent);
			_mapGridLayer.removeEventListener(MouseEvent.MOUSE_OUT, __onGridLayerMouseEvent);
		}
		
		private function __onToolTypeChange(evt:MapEditorEvent):void
		{
			setItemsSelectStage(false);
			_mapGridLayer.removeEventListener(MouseEvent.CLICK, __onGridLayerMouseEvent);
			_mapGridLayer.removeEventListener(MouseEvent.MOUSE_MOVE, __onGridLayerMouseEvent);
			_mapGridLayer.removeEventListener(MouseEvent.MOUSE_OUT, __onGridLayerMouseEvent);
			
			switch(MapEditorManager.instance.mapEditorModel.toolType)
			{
				case ToolType.TOOL_GRID_SELECT:
					_mapGridLayer.addEventListener(MouseEvent.CLICK, __onGridLayerMouseEvent);
					_mapGridLayer.addEventListener(MouseEvent.MOUSE_MOVE, __onGridLayerMouseEvent);
					_mapGridLayer.addEventListener(MouseEvent.MOUSE_OUT, __onGridLayerMouseEvent);
					break;
			}
		}
		
		private function __onGridLayerMouseEvent(evt:MouseEvent):void
		{
			switch(evt.type)
			{
				case MouseEvent.CLICK:
					
					break;
				case MouseEvent.MOUSE_MOVE:
					if(MapEditorManager.instance.mapEditorModel.toolType==ToolType.TOOL_GRID_SELECT)
					{
						_overGridTile.visible=true;
						_overGridTile.point=new Point(evt.localX, evt.localY);
					}
					break;
				case MouseEvent.MOUSE_OUT:
					_overGridTile.visible=false;
					break;
			}
		}
		
		private function __onEditAreaChange(evt:Event):void
		{
			resetEditAreaInfo();
		}
		
		private function resetEditAreaInfo():void
		{
			_mapGridLayer.visible=MapEditorManager.instance.mapEditorModel.editAreaVO.visibleGrid;
			for each(var resItemEditItemView:ResItemEditItemView in _items)
			{
				resItemEditItemView.visible=MapEditorManager.instance.mapEditorModel.editAreaVO.visibleAsset;
			}
		}
		
		private function __onComboAllKeyDown(evt:KeyEvent):void
		{
			var keyComboCell:KeyComboCell=evt.data as KeyComboCell;
			if(keyComboCell.type!="itemSelectItemMove")return;
			
			_moveTimer.addEventListener(TimerEvent.TIMER, moveSelectItem);
			_moveTimer.start();
			
			switch(keyComboCell.data)
			{
				case Keyboard.UP:
					_moveSelectType=1;
					break;
				case Keyboard.DOWN:
					_moveSelectType=2;
					break;
				case Keyboard.LEFT:
					_moveSelectType=3;
					break;
				case Keyboard.RIGHT:
					_moveSelectType=4;
					break;
			}
			moveSelectItem();
		}
		
		private function moveSelectItem(evt:TimerEvent=null):void
		{
			for each(var resItemEditItemView:ResItemEditItemView in _selectResItemEditItemList)
			{
				switch(_moveSelectType)
				{
					case 1:
						resItemEditItemView.z-=1;
						break;
					case 2:
						resItemEditItemView.z+=1;
						break;
					case 3:
						resItemEditItemView.x-=1;
						break;
					case 4:
						resItemEditItemView.x+=1;
						break;
				}
				resItemEditItemView.resItemItemVO.change();
			}
		}
		
		private function __onKeyUp(evt:KeyEvent):void
		{
			_moveTimer.stop();
			_moveTimer.removeEventListener(TimerEvent.TIMER, moveSelectItem);
		}
		
		private function __onResItemItemAssetItemSelected(evt:MapEditorEvent):void
		{
			if(_resItemVO)
			{
				var resItemItemVO:ResItemItemVO=new ResItemItemVO();
				resItemItemVO.assetID=(evt.date as AssetVO).id;
				_resItemVO.addItem(resItemItemVO);
			}
		}
		
		private function __onMouseMove(evt:MouseEvent):void
		{
			//			var p:Point = new Point(_mapGridLayer.mouseX, _mapGridLayer.mouseY);
			switch(MapEditorManager.instance.mapEditorModel.toolType)
			{
				case ToolType.TOOL_SELECT://选择工具
					if(evt.buttonDown)
					{
						if(_selectResItemEditItemList.length>0)
						{
							mouseMoveSelectItem();
						}
						else
						{
							_dragRec.width=mouseX-_dragRec.x;
							_dragRec.height=mouseY-_dragRec.y;
							drawDragRec();	
						}
					}
					break;
			}
		}
		
		/**
		 *移动已选中的项资源 
		 * 
		 */		
		private function mouseMoveSelectItem():void
		{
			for each(var resItemEditItemView:ResItemEditItemView in _selectResItemEditItemList)
			{
				resItemEditItemView.position=IsoUtils.screenToSpace(new Point(_assetLayer.mouseX-resItemEditItemView.mousePoint.x, _assetLayer.mouseY-resItemEditItemView.mousePoint.y));
			}
		}
		
		/**
		 *检查指定的项资源是否已经存在于已选中的项资源列表中 
		 * @param resItemEditItemView
		 * @return 
		 * 
		 */
		private function checkIsExistSelectList(resItemEditItemView:ResItemEditItemView):Boolean
		{
			for each(var item:ResItemEditItemView in _selectResItemEditItemList)
			{
				if(item==resItemEditItemView)return true;
			}
			return false;
		}
		
		/**
		 *是否拖动已选择的项资源列表 
		 * @param isDrag
		 * 
		 */		
		private function dragSelectList(isDrag:Boolean):void
		{
			for each(var resItemEditItemView:ResItemEditItemView in _selectResItemEditItemList)
			{
				if(isDrag)
				{
					resItemEditItemView.startDrag();
				}
				else
				{
					resItemEditItemView.stopDrag();
				}
			}
		}
		
		private function __onMouseDown(evt:MouseEvent):void
		{
			addEventListener(MouseEvent.MOUSE_UP, __onMouseUp);
			switch(MapEditorManager.instance.mapEditorModel.toolType)
			{
				case ToolType.TOOL_SELECT://选择工具
					selectResItemEditItem(evt);
					break;
			}
		}
		
		private function __onMouseOut(evt:MouseEvent):void
		{
		}
		
		private function selectResItemEditItem(evt:MouseEvent):void
		{
			var arrObject:Array = StageReflection.stage.getObjectsUnderPoint(new Point(stage.mouseX, stage.mouseY));
			arrObject=arrObject.reverse();
			if(arrObject && arrObject.length>0)
			{
				var resItemEditItem:ResItemEditItemView;
				for(var i:int=0;i<arrObject.length;i++)
				{
					resItemEditItem=null;
					if(arrObject[i] is ResItemEditItemView)
					{
						resItemEditItem=arrObject[i] as ResItemEditItemView;
					}
					else if((arrObject[i].parent) is ResItemEditItemView)
					{
						resItemEditItem=(arrObject[i].parent) as ResItemEditItemView;
					}
					if(resItemEditItem)
					{
						if(!checkIsExistSelectList(resItemEditItem))
						{
							_selectResItemEditItemList.length=0;
							setItemsSelectStage(false);
							resItemEditItem.resItemItemVO.selected=true;
							resItemEditItem.resItemItemVO.change();
							_selectResItemEditItemList.push(resItemEditItem);
						}
						break;
					}
				}
				if(!resItemEditItem)_selectResItemEditItemList.length=0;
			}
			else
			{
				_selectResItemEditItemList.length=0;
			}
			if(_selectResItemEditItemList.length<=0)
			{//如果当前没有选择中项资源
				setItemsSelectStage(false);
				_dragRec.x=mouseX;
				_dragRec.y=mouseY;
			}
			else
			{
				for each(var resItemEditItemView:ResItemEditItemView in _selectResItemEditItemList)
				{
					resItemEditItemView.mousePoint.x=resItemEditItemView.mouseX;
					resItemEditItemView.mousePoint.y=resItemEditItemView.mouseY;
				}
			}
			
			if(_selectResItemEditItemList.length==1)
			{//如果只有一个选择项，就显示当前这个选择项的属性
				MapEditorManager.instance.selectResItemItemAsset(_selectResItemEditItemList[0].resItemItemVO);
			}
			else
			{
				MapEditorManager.instance.selectResItemItemAsset(null);//发送当前选择项为空，相应的地方会有处理
			}
		}
		
		/**
		 *设置项资源列表中的所有资源的选择状态 
		 * @param selected
		 * 
		 */		
		private function setItemsSelectStage(selected:Boolean):void
		{
			for each(var resItemEditItemView:ResItemEditItemView in _items)
			{
				resItemEditItemView.resItemItemVO.selected=selected;
				resItemEditItemView.resItemItemVO.change();
			}
		}
		
		private function __onMouseUp(evt:MouseEvent):void
		{
			removeEventListener(MouseEvent.MOUSE_UP, __onMouseUp);
			dragRecSelect();
		}
		
		//		private function __onStageMouseUp(evt:MouseEvent):void
		//		{
		//			dragRecSelect();
		//		}		
		
		/**
		 * 矩形区域内的项资源选择处理
		 * 
		 */		
		private function dragRecSelect():void
		{
			if(_selectResItemEditItemList.length>0)
			{
				dragSelectList(false);
			}
			else
			{
				_dragRecLayer.graphics.clear();
				_selectResItemEditItemList.length=0;
				_dragRec.width=mouseX-_dragRec.x;
				_dragRec.height=mouseY-_dragRec.y;
				if(_dragRec.width<0)
				{
					_dragRec.x=_dragRec.x+_dragRec.width;
					_dragRec.width=Math.abs(_dragRec.width);
				}
				if(_dragRec.height<0)
				{
					_dragRec.y=_dragRec.y+_dragRec.height;
					_dragRec.height=Math.abs(_dragRec.height);
				}
				
				for each(var resItemEditItemView:ResItemEditItemView in _items)
				{
					if(_dragRec.containsRect(resItemEditItemView.getRect(this)))
					{
						resItemEditItemView.resItemItemVO.selected=true;
						resItemEditItemView.resItemItemVO.change();
						_selectResItemEditItemList.push(resItemEditItemView);
					}
				}
			}
			_dragRec.setEmpty();
			if(_selectResItemEditItemList.length==1)
			{//如果只有一个选择项，就显示当前这个选择项的属性
				MapEditorManager.instance.selectResItemItemAsset(_selectResItemEditItemList[0].resItemItemVO);
			}
			else
			{
				MapEditorManager.instance.selectResItemItemAsset(null);//发送当前选择项为空，相应的地方会有处理
			}
		}
		
		private function __onResItemItemSelected(evt:MapEditorEvent):void
		{
			if(_resItemVO)
			{
				_resItemVO.removeEventListener(MapEditorEvent.RES_ITEM_ADD_ITEM, __onResItemAddItem);
				_resItemVO.removeEventListener(MapEditorEvent.RES_ITEM_REMOVE_ITEM, __onResItemItemRemove);
				_resItemVO.removeEventListener(MapEditorEvent.RES_ITEM_PROPERTY_CHANGE, __onResItemItemChange);
				_resItemVO=null;
			}
			_selectResItemEditItemList.length=0;
			
			_resItemVO=evt.date as ResItemVO;
			_resItemVO.addEventListener(MapEditorEvent.RES_ITEM_ADD_ITEM, __onResItemAddItem);
			_resItemVO.addEventListener(MapEditorEvent.RES_ITEM_REMOVE_ITEM, __onResItemItemRemove);
			_resItemVO.addEventListener(MapEditorEvent.RES_ITEM_PROPERTY_CHANGE, __onResItemItemChange);
			_gridRow=_resItemVO.gridRow;
			_gridCols=_resItemVO.gridCols;
			setEditResItem();
		}
		
		private function __onResItemAddItem(evt:MapEditorEvent):void
		{
			var resItemItemVO:ResItemItemVO=evt.date as ResItemItemVO;
			var resItemEditItemView:ResItemEditItemView=new ResItemEditItemView(resItemItemVO);
			resItemEditItemView.mouseEnabled=false;
			_assetLayer.addChild(resItemEditItemView);
			_items.push(resItemEditItemView);
		}
		
		private function __onResItemItemRemove(evt:MapEditorEvent):void
		{
			var resItemItemVO:ResItemItemVO=evt.date as ResItemItemVO;
			for each(var resItemEditItemView:ResItemEditItemView in _items)
			{
				if(resItemEditItemView.resItemItemVO==resItemItemVO)
				{
					_items.splice(_items.indexOf(resItemEditItemView), 1);
					DisplayUtil.dispose(resItemEditItemView);
					resItemEditItemView=null;
					break;
				}
			}
		}
		
		private function __onResItemItemChange(evt:MapEditorEvent):void
		{
			setEditResItem();
		}
		
		private function setEditResItem():void
		{
			clearItems();
			_gridRow=_resItemVO.gridRow;
			_gridCols=_resItemVO.gridCols;
			_mapGridLayer.rowSize=_gridRow;
			_mapGridLayer.colsSize=_gridCols;
			_mapGridLayer.update();
			
			for each(var resItemItemVO:ResItemItemVO in _resItemVO.items)
			{
				var resItemEditItemView:ResItemEditItemView=new ResItemEditItemView(resItemItemVO);
				resItemEditItemView.mouseEnabled=false;
				_assetLayer.addChild(resItemEditItemView);
				_items.push(resItemEditItemView);
			}
			
			for each(var resItemGridVO:MapTerrainTileVO in _resItemVO.grids)
			{
				var isoBoxCell:IsoBox=new IsoBox(ConfigTemplateInfo.instance.mapVO.tileSize, resItemGridVO.height);
				isoBoxCell.point=new Point(resItemGridVO.y*ConfigTemplateInfo.instance.mapVO.tileSize, resItemGridVO.x*ConfigTemplateInfo.instance.mapVO.tileSize-resItemGridVO.bottom);
				isoBoxCell.mouseEnabled=false;
				_mapGridLayer.addChild(isoBoxCell);
				_gridBoxList.push(isoBoxCell);
			}
		}
		
		private function clearItems():void
		{
			while(_items && _items.length>0)
			{
				DisplayUtil.dispose(_items.shift());
			}
		}
		
		private function drawDragRec():void
		{
			_dragRecLayer.graphics.clear();
			_dragRecLayer.graphics.lineStyle(1, 0x000000);
			_dragRecLayer.graphics.drawRect(_dragRec.x,_dragRec.y,_dragRec.width, _dragRec.height);
			_dragRecLayer.graphics.endFill();
		}
		
		private function drawEditArea():void
		{
			graphics.clear();
			graphics.beginFill(0xffffff);
			graphics.drawRect(0,0,_areaRec.width, _areaRec.height);
			graphics.endFill();
		}
		
		public function resize():void
		{
			_mapGridLayer.x=_assetLayer.x=(_areaRec.width-_mapGridLayer.width)/2 + _mapGridLayer.width/2;
			drawEditArea();
		}
		
		private function clearGridBoxList():void
		{
			while(_gridBoxList.length)
			{
				DisplayUtil.dispose(_gridBoxList.shift());
			}
		}
		
		public function dispose():void
		{
			removeEvent();
			if(_moveTimer)
			{
				_moveTimer.stop();
				_moveTimer.removeEventListener(TimerEvent.TIMER, moveSelectItem);
				_moveTimer=null;
			}
			if(_mapGridLayer)
			{
				_mapGridLayer.dispose();
				_mapGridLayer=null;
			}
			_selectResItemEditItemList=null;
			clearItems();
			_items=null;
			if(_resItemVO)
			{
				_resItemVO.removeEventListener(MapEditorEvent.RES_ITEM_ADD_ITEM, __onResItemAddItem);
				_resItemVO.removeEventListener(MapEditorEvent.RES_ITEM_REMOVE_ITEM, __onResItemItemRemove);
				_resItemVO.removeEventListener(MapEditorEvent.RES_ITEM_PROPERTY_CHANGE, __onResItemItemChange);
				_resItemVO=null;
			}
			_areaRec=null;
			_dragRec=null;
			DisplayUtil.dispose(_dragRecLayer);
			_dragRecLayer=null;
			_selectGridList=null;
			clearGridBoxList();
			_gridBoxList=null;
			if(parent)parent.removeChild(this);
		}
	}
}